package com.hanxiaozhang.zookeeper;

import com.hanxiaozhang.Configuration;
import com.hanxiaozhang.exception.DistributedLockException;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * 〈一句话功能简述〉<br>
 * 〈初始化zk客户端单例〉
 *
 * @author hanxinghua
 * @create 2022/9/6
 * @since 1.0.0
 */
@Slf4j
public class ZkClientSingleton {

    private static volatile CuratorFramework client;

    private ZkClientSingleton() {
    }

    public static CuratorFramework getInstance(Configuration config) {
        if (null == client) {
            synchronized (ZkClientSingleton.class) {
                if (null == client) {
                    client = initZkClient(config);
                }
            }
        }
        return client;
    }

    /**
     * 初始化客户端
     * <p>
     *
     * @param config
     * @return
     */
    private static CuratorFramework initZkClient(Configuration config) {

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(config.getZkAddress())
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();
        if (client.getState() == CuratorFrameworkState.STARTED) {
            log.info("Zk客户端启动成功!");
        } else {
            log.error("Zk客户端启动失败!");
            throw new DistributedLockException("Zk客户端启动失败!");
        }
        return client;
    }

}
